package comp9417;

import java.util.Map;

/**
 * Created by huy on 28/05/14.
 */
public class CategorialType implements AttributeType {
    @Override
    public double difference(Object v1, Object v2, Attribute attribute) {
        if (v1 == null) return 1;
        return v1.equals(v2) ? 0 : 1;
    }

    @Override
    public String predict(Classifier classifier, DataPoint point, int k) {
        return classifier.classify(point, k);
    }

    @Override
    public String predictWeighted(Classifier classifier, DataPoint point, int k) {
        return classifier.classifyWeighted(point, k);
    }

    @Override
    public void prune(Attribute attribute) {
        int emptyCount = 0;
        for (Map.Entry<String, Integer> entry : attribute.categories.entrySet()) {
            if (entry.getValue() == 0) {
                emptyCount++;
            }
        }
        attribute.prune = (emptyCount == attribute.categories.size() - 1);
    }

    @Override
    public Object prunedValue(Attribute attribute) {
        for (Map.Entry<String, Integer> entry : attribute.categories.entrySet()) {
            if (entry.getValue() > 0) {
                return entry.getKey();
            }
        }
        return null;
    }

    @Override
    public void addValueToDatapoint(Attribute attribute, DataPoint dataPoint, int index, String[] points) {
        String value = "?".equals(points[index]) ? null : points[index];
        dataPoint.addValue(index, value);
        if (value != null) {
            int count = (attribute.categories.get(value) == null) ? 0 : attribute.categories.get(value);
            count++;
            attribute.categories.put(value, count);
        }
    }
}
